package liu.de.dto;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.node.TextNode;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;

/**
 * @author liude
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonDeserialize(using = MyBean.MyBeanSerializer.class)
@Builder
public class MyBean {
    String type;
    Content content;

    public static class MyBeanSerializer extends JsonDeserializer<MyBean> {
        @Override
        public MyBean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            MyBeanBuilder builder = MyBean.builder();
            TreeNode treeNode = p.readValueAsTree();
            TextNode type = (TextNode) treeNode.get("type");
            TreeNode contentNode = treeNode.get("content");

            Content content;

            String typeStr = type.asText();
            switch (typeStr) {
                case "text":
                    content = p.getCodec().treeToValue(contentNode, TextContent.class);
                    break;
                case "image":
                    content = p.getCodec().treeToValue(contentNode, ImageContent.class);
                    break;
                default:
                    throw new IllegalArgumentException("不能识别type=" + typeStr);
            }

            return builder.type(typeStr)
                    .content(content)
                    .build();
        }

    }
}